<%@page import="entity.Admin"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
Admin admin = (Admin) session.getAttribute("admin");
String deptName = "";
if("部门".equals(admin.getIsSuper())) {
	deptName = admin.getDeptName();
}
%>

<div class="callout callout-left">
	<span class="callout-title text-muted">部门许可分配</span><!-- &nbsp;<span class="glyphicon glyphicon-question-sign"></span> -->
	<a class="btn btn-primary" data-toggle="modal" href="#myModal" id="add_deptlic" style="margin-left: 35px;"><span class="glyphicon glyphicon-plus-sign">&nbsp;新增部门分配</span></a>
</div>

<div class="callout">
	<form class="form-inline" action="" method="post">
		<div class="form-group">
			<label for="deptName_search">部门：</label>
			<select name="deptName_search" id="deptName_search" class="form-control">
				<option value="">--请选择--</option>
			</select>
		</div>
		<div class="form-group">
			<label for="softName_search">软件名称：</label>
			<select name="softName_search" id="softName_search" class="form-control">
				<option value="">--请选择--</option>
			</select>
		</div>&nbsp;&nbsp;&nbsp;
		<a href="javascript:;" class="btn btn-primary" id="doSearch"><span class="glyphicon glyphicon-search">&nbsp;搜索</span></a>
		<!-- <a class="btn btn-info"><span class="glyphicon glyphicon-remove-circle">&nbsp;清除</span></a> -->
	</form>
</div>

<div class="callout callout-white">
	<table class="table table-hover">
		<thead>
		<tr>
			<th>编号</th>
			<th>部门名称</th>
			<th>软件名称</th>
			<th>许可数量</th>
			<th>已分配数量</th>
			<th>已激活数量</th>
			<th>动作</th>
		</tr>
		</thead>
		<tbody id="dlic_content">

		</tbody>
	</table>
</div>


<script>
require.config({
	urlArgs: 'v88',
	baseUrl: '<%=path %>/js',
	paths: {
		jquery: 'jquery-1.9.1.min',
		commmon: 'common',
		bootstrapswitch: 'bootstrap-switch.min',
		md5: 'md5'
	}
});
require(['jquery', 'common', 'bootstrapswitch','md5'], function($, common, md5) {

var workspace = function() {

	var domKey;
	var dataOpt;
	var deptLicenses;
	var departments;
	var softwares;

	var init = function() {
		domKey = common.commData.domKey;
		dataOpt = common.dataOpt;

		departments = common.ajaxLoadData(dataOpt.departmentOpt);
		softwares = common.ajaxLoadData(dataOpt.softwareOpt);

		_initTable();
		_addDeptLicense();
		_search();
	}

	var _initTable = function() {
		deptLicenses = common.ajaxLoadData(dataOpt.deptLicenseOpt);
		dataOpt.deptLicenseOpt.data = {"deptName":encodeURI(encodeURI("<%=deptName %>"))}

		var template = "<tr><th>#row#</th>" +
			"<td>#deptName#</td>" +
			"<td>#softName#</td>" +
			"<td>#licenseNum#</td>" +
			"<td>#assigned#</td>" +
			"<td>#activated#</td>" +
			"<td class='text-primary'>" +
			"<a href='#myModal' class='allot' data-toggle='modal' data-name='#deptName#' data-softs='#softName#' data-num='#licenseNum#' data-assigned='#assigned#'>" +
			"<span class='glyphicon glyphicon-edit'>分配</span></a>" +
			"</td></tr>";

		var row = 0;
		var htmlArr = [];
		var html = "";
		var thisT = "";
		for(var i = 0, n = deptLicenses.length; i < n; i++) {
			thisT = template;
			thisT = thisT.replace(/#row#/g, ++row).replace(/#deptName#/g, deptLicenses[i]["deptName"]).replace(/#softName#/g, deptLicenses[i]["softName"])
				.replace(/#licenseNum#/g, deptLicenses[i]["licenseNum"]).replace(/#assigned#/g, deptLicenses[i]["assigned"])
				.replace(/#activated#/g, deptLicenses[i]["activated"]).replace(/#id#/, deptLicenses[i]["id"]);
			html += thisT;
			if((row !== 0) && (row % common.commData.pageNum === 0)) {
				htmlArr.push(html);
				html = "";
			}
		}
		if("" !== html) {
			htmlArr.push(html);// 插入不满pageNum的几条数据
		}

		var opt = {
			htmlArr: htmlArr,
			content: $("#dlic_content"),
		}
		common.pageNav(opt, function() {
			allot();
		});
	}

	// 新建分配
	var _addDeptLicense = function() {
		var modalBodyTemplate = "<form class='form-horizontal'>" +
			"<div class='form-group'>" +
			"<label for='deptName' class='col-sm-4 control-label'>部门名称</label>" +
			"<div class='col-sm-8'>" +
			"<select class='form-control' name='deptName' id='deptName'>" +
			"</select></div></div>" +
			"<div class='form-group'>" +
			"<label for='softName' class='col-sm-4 control-label'>软件名称</label>" +
			"<div class='col-sm-8'>" +
			"<select class='form-control' name='softName' id='softName'>" +
			"</select><span id='helpBlock' class='help-block'></span></div></div>" +
			"<div class='form-group'>" +
			"<label for='licenseNum' class='col-sm-4 control-label'>许可数量</label>" +
			"<div class='col-sm-8'>" +
			"<input type='number' class='form-control' name='licenseNum' id='licenseNum' value='0' min='0' />" +
			"</div></div></form>";

		$("#add_deptlic").click(function() {
			common.cleanModal();
			domKey.modal.find(".modal-dialog").addClass("modal-sm");
			domKey.modalLabel.html("新增部门分配");
			domKey.modalBody.html(modalBodyTemplate);

			// 部门名称
			departments.forEach(function(department) {
				var opt = document.createElement("option");
				$(opt).val(department["deptName"]);
				$(opt).text(department["deptName"]);
				$("#deptName").append(opt);
			});

			// 软件名称
			softwares.forEach(function(software) {
				var opt = document.createElement("option");
				$(opt).val(software["softName"]);
				$(opt).text(software["softName"]);
				$("#softName").append(opt);
			});

			var keyleft;
			// 软件密钥余量
			$("#softName").change(function() {
				for(var i = 0, n = softwares.length; i < n; i++) {
					if($(this).val() === softwares[i]["softName"]) {
						keyleft = softwares[i]["numLicense"] - softwares[i]["assignedLicense"];
						$("#helpBlock").text("剩余可分配密钥数量：" + keyleft);
						break;
					}
				}
			}).change();

			domKey.modalAct.html("新增")
			.on("click", function() {
				common.disable(domKey.modalAct);
				var data = {
					"deptName": encodeURI(encodeURI($("#deptName option:selected").val())),
					"softName": $("#softName option:selected").val(),
					"licenseNum": $("#licenseNum").val()
				}

				if(data["licenseNum"] < 0) {
					swal("提示", "许可数量至少为0", "warning");
					common.enable(domKey.modalAct);
				} else if(data["licenseNum"] > keyleft) {
					swal("提示", "许可数量不得大于密钥剩余数量", "warning");
					common.enable(domKey.modalAct);
				} else {
					$.ajax({
						url: "<%=path %>/servlet/dept/AddDeptLicenseServlet",
						data: data,
						dataType: "json",
						async: false,
						success: function(data) {
							if("1" === data["retCode"]) {
								softwares = common.ajaxLoadData(dataOpt.softwareOpt);
							} else {
								alert(data["desc"]);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert("AddDeptLicenseServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
						},
						complete: function() {
							domKey.modal.find(".close").click();
							_initTable();
						}
					});
				}
			});
		});
	}

	// 部门分配
	var allot = function() {
		var modalBodyTemplate = "<form class='form-horizontal'>" +
			"<div class='form-group'>" +
			"<label for='deptName' class='col-sm-4 control-label'>部门名称</label>" +
			"<div class='col-sm-8'>" +
			"<input type='text' class='form-control' name='deptName' id='deptName' readonly />" +
			"</div></div>" +
			"<div class='form-group'>" +
			"<label for='softName' class='col-sm-4 control-label'>软件名称</label>" +
			"<div class='col-sm-8'>" +
			"<input type='text' class='form-control' name='softName' id='softName' readonly />" +
			"<span id='helpBlock' class='help-block'></span></div></div>" +
			"<div class='form-group'>" +
			"<label for='licenseNum' class='col-sm-4 control-label'>许可数量</label>" +
			"<div class='col-sm-8'>" +
			"<input type='number' class='form-control' name='licenseNum' id='licenseNum' />" +
			"</div></div></form>";

		$(".allot").each(function() {
			var deptName = $(this).data("name");
			var softName = $(this).data("softs");
			var licenseNum = $(this).data("num");
			var assigned = $(this).data("assigned");

			$(this).click(function() {
				common.cleanModal();
				domKey.modal.find(".modal-dialog").addClass("modal-sm");
				domKey.modalLabel.html("修改许可数量");
				domKey.modalBody.html(modalBodyTemplate);

				$("#deptName").val(deptName);
				$("#softName").val(softName);
				$("#licenseNum").val(licenseNum);

				// 软件密钥余量
				var keyleft;
				for(var i = 0, n = softwares.length; i < n; i++) {
					if($("#softName").val() === softwares[i]["softName"]) {
						keyleft = softwares[i]["numLicense"] - softwares[i]["assignedLicense"];
						$("#helpBlock").text("剩余可分配密钥数量：" + keyleft);
						break;
					}
				}

				domKey.modalAct.html("保存")
				.on("click", function() {
					common.disable(domKey.modalAct);
					if($("#licenseNum").val() < assigned) {
						swal("提示", "许可数量至少为0", "warning");
						common.enable(domKey.modalAct);
					} else if($("#licenseNum").val() > keyleft) {
						swal("提示", "许可数量不得大于密钥剩余数量", "warning");
						common.enable(domKey.modalAct);
					} else {
						$.ajax({
							url: "<%=path %>/servlet/dept/EditLicenseNumServlet",
							type: "post",
							data: {"deptName": deptName,"softName":softName,"licenseNum":$("#licenseNum").val()},
							dataType: "json",
							success: function(data) {
								if("1" === data["retCode"]) {
									// 重新加载软件密钥数量
									softwares = common.ajaxLoadData(dataOpt.softwareOpt);
								} else {
									alert(data["desc"]);
								}
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								alert("服务器错误:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
							},
							complete: function() {
								domKey.modal.find(".close").click();
								_initTable();
							}
						});
					}
				});
			});
		});
	}

	// 搜索
	var _search = function() {

		// 部门
		if("<%=admin.getIsSuper() %>" === "部门") {
			$("#deptName_search").addClass("a-disabled").attr("readonly",true);
		} else {
			departments.forEach(function(department) {
				var opt = document.createElement("option");
				$(opt).val(department["deptName"]);
				$(opt).text(department["deptName"]);
				$("#deptName_search").append(opt);
			});
		}

		// 软件
		softwares.forEach(function(software) {
			var opt = document.createElement("option");
			$(opt).val(software["softName"]);
			$(opt).text(software["softName"]);
			$("#softName_search").append(opt);
		});

		$("#doSearch").click(function() {
			dataOpt.deptLicenseOpt.data = {
				"deptName": encodeURI(encodeURI($("#deptName_search").val())),
				"softName": encodeURI(encodeURI($("#softName_search").val()))
			}
			_initTable();
		});

	}

	return {
		init: init
	}
}();

$(function() {	workspace.init(); });

});

requirejs.onError = function (err) {
	console.error(err);
	if (err.requireType === 'timeout') {
		console.error('modules: ' + err.requireModules);
	}
	throw err;
}
</script>